package com.mojiayi.learn.jwt.controller;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.mojiayi.learn.common.response.CommunicationFactory;
import com.mojiayi.learn.common.response.CommunicationResponse;
import com.mojiayi.learn.jwt.system.annotation.VerifyWithJWT;
import com.mojiayi.learn.jwt.system.constant.UserInfoConstant;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/jwt-demo")
public class JwtDemoController {
    @VerifyWithJWT
    @RequestMapping("/need-check")
    public CommunicationResponse needLoginCheck(String userId) {
        CommunicationResponse response = CommunicationFactory.createCommunicationResponse();
        response.addSingleDataItem("userId", userId);
        response.addSingleDataItem("timestamp", System.currentTimeMillis());
        return response;
    }

    @RequestMapping("/login")
    public CommunicationResponse login(String userId) {
        CommunicationResponse response = CommunicationFactory.createCommunicationResponse();
        response.addSingleDataItem("token", generateToken(userId, UserInfoConstant.TEST_USER_PWD));
        response.addSingleDataItem("timestamp", System.currentTimeMillis());
        return response;
    }

    private String generateToken(String userId, String userPwd) {
        return JWT.create().withAudience(userId)
                .sign(Algorithm.HMAC256(userPwd));
    }
}
